package com.lut.reservation.config;

import com.lut.reservation.bean.RoomReservation;
import com.lut.reservation.bean.User;
import com.lut.reservation.service.RoomReservationService;
import com.lut.reservation.service.UserService;
import com.lut.reservation.service.impl.MailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;
import java.util.List;

@Slf4j
@Configuration
@EnableScheduling
public class ScheduleTask {

  @Autowired
  private RoomReservationService reservationService;

  @Autowired
  private MailService mailService;

  @Autowired
  private UserService userService;

  private static final String TITLE = "预约即将开始";
  private static final String CONTEXT = "您所预约的多功能厅使用期限即将开始，请您按时到达并且使用。";

  //或直接指定时间间隔，例如：5秒 @Scheduled(fixedRate=5000)
  @Scheduled(cron = "0 */1 * * * ?")
  public void tasks() {
    log.info("定时任务执行开始");
    Date endDate = DateUtils.addHours(new Date(), 3);
    // select * from room_reservation where start_time <= DATE_ADD(NOW(), INTERVAL 3 HOUR) and start_time >= NOW();
    List<RoomReservation> list = reservationService.lambdaQuery()
        .eq(RoomReservation::getState, "PASS")
        .eq(RoomReservation::getSendEmail, 0)
        .between(RoomReservation::getStartTime, new Date(), endDate)
        .list();
    list.forEach(roomReservation -> {
      Integer userId = roomReservation.getUserId();
      User user = userService.getById(userId);
      if (userId != null && user != null) {
        RoomReservation reservation = new RoomReservation();
        reservation.setSendEmail(1);
        reservation.setId(roomReservation.getId());
        reservationService.updateById(reservation);
        mailService.sendSimpleMail(user.getEmail(), TITLE, CONTEXT);
      }
    });
    log.info("短信服务执行完毕");
  }
}

